import { Loading,Message  } from 'element-ui';
import route from "../router/index.js"

// =====打包的时候打开下列
// ==正式服务器地址
// var root = '';
// var devApi = '';

// =====开发的时候打开下列
var root = '';
var devApi = 'api';
// 在这边来区分开 api 和 zhumu 的封装地址，用判断
// var devApi = '/api';

var loadinginstace;

var axios = require('axios')
var qs = require('qs')

function toType (obj) {
  return ({}).toString.call(obj).match(/\s([a-zA-Z]+)/)[1].toLowerCase()
}

function filterNull (o) {
  for (var key in o) {
    if (o[key] === null) {
      delete o[key]
    }
    if (toType(o[key]) === 'string') {
      o[key] = o[key].trim()
    } else if (toType(o[key]) === 'object') {
      o[key] = filterNull(o[key])
    } else if (toType(o[key]) === 'array') {
      o[key] = filterNull(o[key])
    }
  }
  return o
}

function apiAxios (method, url, params, success, failure) {
  // loadinginstace = Loading.service({ target: "#contentRigh"})
  if (params) {
    params = filterNull(params)
  }
  axios({
    method: method,
    url: devApi + url,
    data: method === 'POST' || method === 'PUT' ? params : null,
    params: method === 'GET' || method === 'DELETE' ? params : null,
    transformRequest: [function (params) {
      return qs.stringify(params, {arrayFormat: 'brackets'});
    }],
    headers:{
      'Content-Type':'application/x-www-form-urlencoded; chartset=UTF-8'
    },
    baseURL: root,
    withCredentials: false
  })
  .then(function (res) {
    (function(){
      // loadinginstace.close();
    })();
    if (res.data.errCode == 0) {
      if (success) {
        success(res.data)
      }
    } else {
      if (failure) {
        failure(res.data)
      } else {
        // window.alert('error: ' + JSON.stringify(res.data))
        if(res.data.Message=="请先登录"){
          route.push("/");
          $(".modal-backdrop").fadeOut("fast")
        }
        Message.error({
          showClose:true,
          message:res.data.Message,
          duration:2000,
          type: 'error'
        })
      }
    }
  })
  .catch(function (err) {
    (function(){
      // loadinginstace.close();
    })();
    let res = err;
    if (res) {
      // window.alert('api error, HTTP CODE: ' + res.status);
      if(res.data==undefined){
          Message.error({
            showClose:true,
            message:"网络异常，请刷新浏览器重试！",
            duration:1500,
            type: 'error'
          })
        }else{
          let err=JSON.stringify(res.message);
          Message.error({
            showClose:true,
            message:err,
            duration:1500,
            type: 'error'
          })
        }
      return
    }
  })
  // loadinginstace.close();  
}

// 封装JSON
function apiAxiosJson(method, url, params, success, failure) {
  // loadinginstace = Loading.service({ target: "#contentRigh"})
  if (params) {
    params = filterNull(params)
  }
  axios({
    method: method,
    url: devApi + url,
    data: method === 'POST' || method === 'PUT' ? params : null,
    params: method === 'GET' || method === 'DELETE' ? params : null,
    // 
    headers: {
      'Content-Type': 'application/json'
    },
    baseURL: root,
    withCredentials: false
  })
    .then(function (res) {
      (function () {
        // loadinginstace.close();
      })();
      if (res.data.errCode == 0) {
        if (success) {
          success(res.data)
        }
      } else {
        if (failure) {
          failure(res.data)
        } else {
          // window.alert('error: ' + JSON.stringify(res.data))
          if (res.data.Message == "请先登录") {
            route.push("/");
            $(".modal-backdrop").fadeOut("fast")
          }
          Message.error({
            showClose: true,
            message: res.data.Message,
            duration: 2000,
            type: 'error'
          })
        }
      }
    })
    .catch(function (err) {
      (function () {
        // loadinginstace.close();
      })();
      let res = err;
      if (res) {
        // window.alert('api error, HTTP CODE: ' + res.status);
        if (res.data == undefined) {
          Message.error({
            showClose: true,
            message: "网络异常，请刷新浏览器重试！",
            duration: 1500,
            type: 'error'
          })
        } else {
          let err = JSON.stringify(res.message);
          Message.error({
            showClose: true,
            message: err,
            duration: 1500,
            type: 'error'
          })
        }
        return
      }
    })
  // loadinginstace.close();  
}

// 接口封装
export default {
  get: function (url, params, success, failure) {
    return apiAxios('GET', url, params, success, failure)
  },
  post: function (url, params, success, failure) {
    return apiAxios('POST', url, params, success, failure)
  },
  // JSON 格式封装
  postJson: function (url, params, success, failure) {
    return apiAxiosJson('POST', url, params, success, failure)
  },
  put: function (url, params, success, failure) {
    return apiAxios('PUT', url, params, success, failure)
  },
  delete: function (url, params, success, failure) {
    return apiAxios('DELETE', url, params, success, failure)
  }
}
